package br.com.sgp.util.handling;

import org.apache.log4j.Logger;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.attributes.AjaxCallListener;
import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.IModel;

import br.com.sebrae.pr.sgp.util.exceptions.ExcecaoDeApresentacao;
import br.com.sebrae.pr.sgp.util.exceptions.TipoErro;
import br.com.sebrae.pr.sgp.util.exceptions.TratadorDeExcecoes;
import br.com.ufpr.util.base.BasePage;

public abstract class ErrorHandlingAjaxSubmitConfirmLink extends AjaxSubmitLink {
    private static final long serialVersionUID = -4044283312866762093L;

    private static final Logger log = Logger.getLogger(ErrorHandlingAjaxSubmitConfirmLink.class);

    private final IModel<String> confirmMessage;

    public ErrorHandlingAjaxSubmitConfirmLink(final String id, final Form<?> form, final IModel<String> confirmMessage) {
        super(id, form);
        this.confirmMessage = confirmMessage;
    }

    @Override
    protected void onSubmit(AjaxRequestTarget target, Form<?> form) {

        try {
            log.debug("Iniciando click ajax.");
            onClicked(target);
            onSucesso(target);
            log.debug("Término da exucução do click ajax.");

        } catch (Exception e) {
            TratadorDeExcecoes.logaException("Erro no click ajax...", e);
            onErro(target);

            final ExcecaoDeApresentacao ea = TratadorDeExcecoes.convertException(e);
            ((BasePage) ErrorHandlingAjaxSubmitConfirmLink.this.getPage()).adicionaMensagem(ea.getTipoErro() != null ? ea.getTipoErro()
                    : TipoErro.ERRO, ea.getMensagem());
            ((BasePage) ErrorHandlingAjaxSubmitConfirmLink.this.getPage()).atualizarFeedbackPanel();
        }
    }

    protected void onSucesso(final AjaxRequestTarget target) {
    }

    protected void onErro(final AjaxRequestTarget target) {
    }

    protected abstract void onClicked(final AjaxRequestTarget target);

    @Override
    protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
        super.updateAjaxAttributes(attributes);
        final AjaxCallListener ajaxCallListener = new AjaxCallListener();
        ajaxCallListener.onPrecondition("return confirm('" + confirmMessage.getObject() + "');");
        attributes.getAjaxCallListeners().add(ajaxCallListener);
    }

}
